<template>
  <el-upload
    class="avatar-uploader"
    :action="$store.state.app.uploadUrl"
    :show-file-list="false"
    :headers="headers"
    :on-progress="handleProgress"
    :on-error="handleError"
    :on-success="handleSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import { getToken } from '../utils/auth'

export default {
  name: 'UploadAvatar',
  props: {
    value: {
      type: [String],
      required: true
    }
  },
  data() {
    return {
      oss: null,
      loading: null,
      headers: {
        Authorization: 'bearer' + getToken(),
        Accept: 'application/json'
      }
    }
  },
  mounted() {
    this.getOssConfig()
  },
  methods: {
    getOssConfig() {

    },
    handleProgress() {
      this.loading = this.$loading({
        text: '玩儿命上传中..',
        background: 'rgba(0, 0, 0, 0.8)'
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      console.log(!(isJPG || isPNG), file)

      const condition = !(isJPG || isPNG)
      if (condition) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return !condition && isLt2M
    },
    handleSuccess(response, file, fileList) {
      if (this.loading) {
        this.loading.close()
      }
      this.$message.success('上传成功')
      this.$emit('input', response.url)
    },
    handleError() {
      if (this.loading) {
        this.loading.close()
      }
      this.$message.success('上传失败')
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
